package com.billsystem.controller;


import com.billsystem.pojo.Category;
import com.billsystem.service.CategoryService;
import com.billsystem.service.RecordService;
import com.billsystem.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@RestController
public class CategoryController {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RecordService recordService;
    @Autowired
    private HttpSession session;
    /*
    增加消费收入种类
     */
    @PostMapping("/addCategory")
    public Object addCategory(@RequestBody Category category){
        try{
            int uid = (int)session.getAttribute("userId");
            category.setUid(uid);
            //System.out.println(category.getName()+" "+category.getUid());
            categoryService.addCategory(category);
            return Result.success();
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("error");
        }
    }
    /*
    获取全部单类型的种类
     */
    @GetMapping("/listCategory/{incomeExpend}")
    public Object listCategory(@PathVariable char incomeExpend){
        int uid = (int)session.getAttribute("userId");
        //根据用户id和incomeExpend查询种类
        List<Category> lists = categoryService.queryListByUid(uid, incomeExpend);
        List<Category> res = new ArrayList<>();
        for (Category temp : lists) {
            //获取种类id
            int cid = temp.getId();
            //获取种类次数
            int count = recordService.queryCountOfCategory(cid, uid);
            //获取该分类的所涉及的总金额
            double totalMoney = recordService.queryCountOfSpend(cid, uid);

            temp.setCount(count);
            temp.setTotalMoney(totalMoney);
            res.add(temp);
        }
        try{
            return Result.success(res);
        }catch (Exception e){
            return Result.fail("error");
        }
    }

    //因为数据量大，所以就没有用delete的请求来操作
    @PostMapping("/deleteCategory")
    public Object deleteCategory(@RequestBody Category category){
        try{
            int uid = (int)session.getAttribute("userId");
            category.setUid(uid);
            categoryService.deleteCategory(category);
            return Result.success();
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("error");
        }
    }
    /*
    更新种类
     */
    @PutMapping("/updateCategory")
    public Object updateCategory(@RequestBody Category category){
        try{
            int uid = (int)session.getAttribute("userId");
            category.setUid(uid);
            categoryService.updateCategory(category);
            return Result.success();
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("error");
        }
    }

}
